<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-wrapper">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="部门" prop="department_id">
          <el-tree-select
            v-model="queryParams.department_id"
            :data="departmentOptions"
            placeholder="请选择部门"
            clearable
            :props="{ label: 'name', value: 'id', children: 'children' }"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card shadow="never" class="table-wrapper">
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增
          </el-button>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="userList" border style="width: 100%">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="username" label="用户名" min-width="100" show-overflow-tooltip />
        <el-table-column prop="name" label="姓名" min-width="100" show-overflow-tooltip />
        <el-table-column prop="department_name" label="部门" min-width="120" show-overflow-tooltip />
        <el-table-column prop="email" label="邮箱" min-width="150" show-overflow-tooltip />
        <el-table-column prop="phone" label="手机号" min-width="120" show-overflow-tooltip />
        <el-table-column label="角色" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag v-for="role in row.roles" :key="role.id" size="small" style="margin-right: 5px">
              {{ role.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleUpdate(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.page_size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="dialogType === 'update'" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="部门" prop="department_id">
          <el-tree-select
            v-model="userForm.department_id"
            :data="departmentOptions"
            placeholder="请选择部门"
            :props="{ label: 'name', value: 'id', children: 'children' }"
          />
        </el-form-item>
        <el-form-item label="角色" prop="role_ids">
          <el-select
            v-model="userForm.role_ids"
            multiple
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { useThemeStore } from '@/store/theme'
import { getUsers, getUser, createUser, updateUser, deleteUser } from '@/api/user'
import { getRoles } from '@/api/role'
import { getDepartmentTree } from '@/api/department'
import { isEmail, isPhone } from '@/utils/validate'

// 查询参数
const queryParams = reactive({
  page: 1,
  page_size: 10,
  username: '',
  name: '',
  department_id: null,
  status: null
})

// 表格数据
const userList = ref([])
const total = ref(0)
const loading = ref(false)

// 部门树形选项
const departmentOptions = ref([])

// 角色选项
const roleOptions = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // add 或 update
const dialogTitle = ref('添加用户')
const userFormRef = ref(null)
const queryFormRef = ref(null)

// 用户表单
const userForm = reactive({
  id: null,
  username: '',
  name: '',
  password: '',
  email: '',
  phone: '',
  department_id: null,
  role_ids: [],
  status: true
})

// 表单校验规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: false, message: '请输入邮箱', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value && !isEmail(value)) {
        callback(new Error('请输入正确的邮箱格式'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ],
  phone: [
    { required: false, message: '请输入手机号', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value && !isPhone(value)) {
        callback(new Error('请输入正确的手机号格式'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ],
  department_id: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  role_ids: [
    { required: true, message: '请选择角色', trigger: 'change' },
    { type: 'array', min: 1, message: '请至少选择一个角色', trigger: 'change' }
  ]
}

// 获取用户列表
const getUserList = async () => {
  loading.value = true
  try {
    const res = await getUsers(queryParams)
    userList.value = res.data
    total.value = res.page_info.total
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取部门树形数据
const getDepartmentTreeData = async () => {
  try {
    const res = await getDepartmentTree()
    departmentOptions.value = res.data
  } catch (error) {
    console.error('获取部门树形数据失败:', error)
  }
}

// 获取角色列表
const getRoleList = async () => {
  try {
    const res = await getRoles({ page: 1, page_size: 100 })
    roleOptions.value = res.data
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

// 查询
const handleQuery = () => {
  queryParams.page = 1
  getUserList()
}

// 重置查询
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  getUserList()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  queryParams.page_size = size
  getUserList()
}

// 添加用户
const handleAdd = () => {
  resetUserForm()
  dialogType.value = 'add'
  dialogTitle.value = '添加用户'
  dialogVisible.value = true
}

// 编辑用户
const handleUpdate = async (row) => {
  resetUserForm()
  dialogType.value = 'update'
  dialogTitle.value = '编辑用户'
  
  try {
    const res = await getUser(row.id)
    const userData = res.data
    
    // 填充表单数据
    userForm.id = userData.id
    userForm.username = userData.username
    userForm.name = userData.name
    userForm.email = userData.email
    userForm.phone = userData.phone
    userForm.department_id = userData.department_id
    userForm.status = userData.status
    userForm.role_ids = userData.roles.map(role => role.id)
    
    dialogVisible.value = true
  } catch (error) {
    console.error('获取用户详情失败:', error)
    ElMessage.error('获取用户详情失败')
  }
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除用户 ${row.name} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteUser(row.id)
      ElMessage.success('删除成功')
      getUserList()
    } catch (error) {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }).catch(() => {})
}

// 重置用户表单
const resetUserForm = () => {
  userForm.id = null
  userForm.username = ''
  userForm.name = ''
  userForm.password = ''
  userForm.email = ''
  userForm.phone = ''
  userForm.department_id = null
  userForm.role_ids = []
  userForm.status = true
  
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          // 创建用户
          await createUser(userForm)
          ElMessage.success('添加成功')
        } else {
          // 更新用户
          await updateUser(userForm.id, userForm)
          ElMessage.success('更新成功')
        }
        
        dialogVisible.value = false
        getUserList()
      } catch (error) {
        console.error('保存用户失败:', error)
        ElMessage.error('保存用户失败')
      }
    }
  })
}

onMounted(() => {
  getUserList()
  getDepartmentTreeData()
  getRoleList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 0;
  
  .search-wrapper {
    margin-bottom: 20px;
    border: 1px solid var(--border-color);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
    
    :deep(.el-card__body) {
      background-color: var(--card-bg-color);
      padding: 20px;
    }
    
    :deep(.el-form) {
      .el-form-item {
        margin-bottom: 16px;
        
        .el-form-item__label {
          color: var(--text-color);
          font-weight: 500;
        }
        
        .el-input__wrapper {
          border-radius: 6px;
          transition: all 0.3s ease;
          background-color: var(--card-bg-color);
          
          &:hover {
            border-color: var(--border-color);
          }
          
          &.is-focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          }
        }
        
        .el-select {
          .el-input__wrapper {
            border-radius: 6px;
            background-color: var(--card-bg-color);
          }
        }
        
        .el-button {
          border-radius: 6px;
          font-weight: 500;
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
        }
      }
    }
  }
  
  .table-wrapper {
    border: 1px solid var(--border-color);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
    
    :deep(.el-card__header) {
      background-color: var(--header-bg-color);
      border-bottom: 1px solid var(--border-color);
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .el-button {
          border-radius: 6px;
          font-weight: 500;
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
        }
      }
    }
    
    :deep(.el-card__body) {
      background-color: var(--card-bg-color);
      padding: 20px;
    }
    
    :deep(.el-table) {
      border-radius: 6px;
      overflow: hidden;
      background-color: var(--card-bg-color);
      
      .el-table__header {
        th {
          background-color: var(--header-bg-color);
          color: var(--text-color);
          font-weight: 600;
          border-bottom: 1px solid var(--border-color);
        }
      }
      
      .el-table__body {
        tr {
          background-color: var(--card-bg-color);
          
          &:hover > td {
            background-color: var(--hover-bg-color) !important;
          }
          
          td {
            border-bottom: 1px solid var(--border-color);
            color: var(--text-color);
            
            .el-tag {
              border-radius: 4px;
              font-weight: 500;
            }
            
            .el-button {
              border-radius: 4px;
              font-weight: 500;
              transition: all 0.3s ease;
              color: var(--text-color);
              
              &:hover {
                transform: translateY(-1px);
              }
            }
          }
        }
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    
    :deep(.el-pagination) {
      .el-pager li {
        border-radius: 4px;
        margin: 0 2px;
        transition: all 0.3s ease;
        background-color: var(--card-bg-color);
        color: var(--text-color);
        
        &:hover {
          background-color: var(--hover-bg-color);
        }
        
        &.is-active {
          background-color: #409eff;
          color: #ffffff;
        }
      }
      
      .btn-prev,
      .btn-next {
        border-radius: 4px;
        transition: all 0.3s ease;
        background-color: var(--card-bg-color);
        color: var(--text-color);
        
        &:hover {
          background-color: var(--hover-bg-color);
        }
      }
    }
  }
}

// 对话框样式优化
:deep(.el-dialog) {
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  background-color: var(--card-bg-color);
  
  .el-dialog__header {
    background-color: var(--header-bg-color);
    border-bottom: 1px solid var(--border-color);
    border-radius: 8px 8px 0 0;
    
    .el-dialog__title {
      color: var(--text-color);
      font-weight: 600;
    }
  }
  
  .el-dialog__body {
    background-color: var(--card-bg-color);
    padding: 24px;
    color: var(--text-color);
    
    .el-form {
      .el-form-item {
        margin-bottom: 20px;
        
        .el-form-item__label {
          color: var(--text-color);
          font-weight: 500;
        }
        
        .el-input__wrapper,
        .el-select .el-input__wrapper,
        .el-tree-select .el-input__wrapper {
          border-radius: 6px;
          transition: all 0.3s ease;
          background-color: var(--card-bg-color);
          
          &:hover {
            border-color: var(--border-color);
          }
          
          &.is-focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          }
        }
        
        .el-radio-group {
          .el-radio {
            margin-right: 20px;
            
            .el-radio__label {
              color: var(--text-color);
            }
          }
        }
      }
    }
  }
  
  .el-dialog__footer {
    background-color: var(--header-bg-color);
    border-top: 1px solid var(--border-color);
    border-radius: 0 0 8px 8px;
    
    .dialog-footer {
      .el-button {
        border-radius: 6px;
        font-weight: 500;
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
      }
    }
  }
}
</style>
